<template>
  <form class="image-input-wrapper">
    <div class="image-submit-cover">
      <img ref="cover" :src="imageUrl" alt="image" v-show="imageUrl"
      class="cover-image">
      <span v-show="!imageUrl">upload</span>
    </div>
    <input type="file" name="image" class="image-input" ref="imageInput"
    @input="handleInput($event)">
  </form>
</template>

<script>
  export default {
    emits: ['update:image'],
    props: {
      image: {
        type: File,
        default: null
      },
    },
    data() {
      return {
        imageUrl: ""
      }
    },
    watch: {
      image(newValue) {
        if(!newValue) {
          this.imageUrl = '';
          return;
        }
        if(!(newValue instanceof Blob)) return;
        let reader = new FileReader();
        reader.addEventListener('load', () => {
          this.imageUrl = reader.result;
        });
        reader.readAsDataURL(this.image);
      }
    },
    methods: {
      handleInput(event) {
        this.$emit('update:image', event.target.files[0]);
      }
    },
  }
</script>

<style lang="less" scoped>
@w: var(--imageInputWidth);
@h: var(--imageInputHeight);

.image-input-wrapper {
  position: relative;
  width: @w;
  height: @h;

  .image-input {
    display: block;
    width: @w;
    height: @h;

    position: absolute;
    top: 0;
    left: 0;

    opacity: 0;

    &:hover {
      cursor: pointer;
    }
  }

  .image-submit-cover {
    box-sizing: border-box;
    position: relative;
    width: @w;
    height: @h;
    line-height: @h;
    text-align: center;
    border-radius: calc(@w * 0.05);
    border: 1px dashed var(--gray);
    color: var(--gray);
    transition: .1s;

    .cover-image {
      width: calc(@w * 1.1);
      height: calc(@h * 1.1);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: calc(@w * 0.02);
    }
  }

  &:hover {
    .image-submit-cover {
      color: var(--darkBlue);
      border-color: var(--darkBlue);
    }
  }
}
</style>